using CommunityToolkit.Mvvm.Input;
using Koala.Pro.Common;
using Koala.Pro.Common.Extension;
using Koala.Pro.Core.Models;
using Koala.Pro.Services;
using Koala.Pro.ViewModels;
using System.Data;
using System.Windows.Controls;
using Wpf.Ui.Controls;

namespace Koala.Pro.Views.Pages;

public partial class BlackIPListPage : Page, INavigableView<BlackIPListViewModel>
{
    public BlackIPListViewModel ViewModel { get; }

    public BlackIPListPage(BlackIPListViewModel viewModel)
    {
        ViewModel = viewModel;
        DataContext = this;

        InitializeComponent();

        // this.ViewModel.PageDto.SystemType_ID = App.ViewModel.SystemType;
    }

    [RelayCommand]
    private async Task Add()
    {
        await this.Edit(null);
    }

    [RelayCommand]
    private async Task EditById(string id)
    {
        if (id.IsNullOrEmpty())
            return;

        var page = App.GetService<BlackIPEditPage>();
        page.ViewModel.Item = await BLLFactory<IBlackIPService>.Instance.GetAsync(id);

        await page.ViewModel.InitData(id);
        page.ViewModel.IsEdit = true;
        page.ShowDialog();
        if (page.ViewModel?.Result?.Success == true)
        {
            await this.ViewModel.GetData();
        }
    }

    [RelayCommand]
    private async Task Edit(BlackIPInfo info)
    {
        var page = App.GetService<BlackIPEditPage>();
        if (info != null)
        {
            page.ViewModel.Item = await BLLFactory<IBlackIPService>.Instance.GetAsync(info.Id);
            await page.ViewModel.InitData(info.Id);
            page.ViewModel.IsEdit = true;
        }
        else
        {
            page.ViewModel.Item = new BlackIPInfo()
            {
                //Creator = App.ViewModel.UserInfo.Id.ToString(),
                //Editor = App.ViewModel.UserInfo.Id.ToString(),
                //EditTime = DateTime.Now,
            };
            page.ViewModel.NotifyChanged();
            page.ViewModel.IsEdit = false;
        }

        page.ShowDialog();
        if (page.ViewModel.Result?.Success == true)
        {
            await this.ViewModel.GetData();
        }
    }

    [RelayCommand]
    private async Task Delete(BlackIPInfo info)
    {
        await ViewModel.DeleteCommand.ExecuteAsync(info);
        await this.ViewModel.GetData();
    }

    [RelayCommand]
    private void Search()
    {
        // 重置某些条件
        //this.ViewModel.PageDto.Dept_ID = null; //置空条件查询
        //this.ViewModel.PageDto.Role_ID = null;//置空条件查询

        this.ViewModel.SearchCommand.ExecuteAsync(null);
    }

    private void DataGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        if (!(sender is System.Windows.Controls.DataGrid { SelectedItems: var selectedItems }))
        {
            return;
        }
        if (selectedItems != null)
        {
            var list = new List<BlackIPInfo>();
            foreach (BlackIPInfo info in selectedItems)
            {
                list.Add(info);
            }
            ViewModel.SelectedItems = list;
        }
        else
        {
            ViewModel.SelectedItems = null;
        }
    }

    [RelayCommand]
    private void ImportExcel()
    {
        var page = App.GetService<ImportExcelPage>();
        page.ViewModel.Items?.Clear();
        page.ViewModel.TemplateFile = $"BlackIP-模板.xls";
        page.OnDataSave -= ExcelData_OnDataSave;
        page.OnDataSave += ExcelData_OnDataSave;
        ViewModel.Navigate(typeof(ImportExcelPage));
    }

    private string GetRowData(DataRow row, string columnName)
    {
        string result = "";
        if (row.Table.Columns.Contains(columnName))
        {
            result = row[columnName].ToString();
        }
        return result;
    }

    private async Task<bool> ExcelData_OnDataSave(DataRow dr)
    {
        bool converted = false;
        DateTime dtDefault = Convert.ToDateTime("1900-01-01");
        DateTime dt;
        var info = new BlackIPInfo();
        info.Id = GetRowData(dr, "ID");
        info.Name = GetRowData(dr, "Name");
        info.AuthorizeType = GetRowData(dr, "AuthorizeType").ToInt32();
        info.Forbid = GetRowData(dr, "Forbid").ToInt32();
        info.IPStart = GetRowData(dr, "IPStart");
        info.IPEnd = GetRowData(dr, "IPEnd");
        info.Note = GetRowData(dr, "Note");
        info.Creator = GetRowData(dr, "Creator");
        info.Creator_ID = GetRowData(dr, "Creator_ID");

        string CreateTime = GetRowData(dr, "CreateTime");
        if (!string.IsNullOrEmpty(CreateTime))
        {
            converted = DateTime.TryParse(CreateTime, out dt);
            if (converted && dt > dtDefault)
            {
                info.CreateTime = dt;
            }
        }
        else
        {
            info.CreateTime = DateTime.Now;
        }

        info.Editor = GetRowData(dr, "Editor");
        info.Editor_ID = GetRowData(dr, "Editor_ID");

        string EditTime = GetRowData(dr, "EditTime");
        if (!string.IsNullOrEmpty(EditTime))
        {
            converted = DateTime.TryParse(EditTime, out dt);
            if (converted && dt > dtDefault)
            {
                info.EditTime = dt;
            }
        }
        else
        {
            info.EditTime = DateTime.Now;
        }

        var success = await BLLFactory<IBlackIPService>.Instance.InsertAsync(info);
        return success;
    }
}
